package yc.star.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import yc.star.common.constants.HttpConstants;
import yc.star.common.domain.AppResult;
import yc.star.common.domain.LoginUser;
import yc.star.common.domain.vo.LoginUserVo;
import yc.star.common.enums.ResultCode;
import yc.star.common.enums.UserIdentity;
import yc.star.common.security.exception.ApplicationException;
import yc.star.common.security.service.TokenService;
import yc.star.system.domain.sysuser.SysUser;
import yc.star.system.domain.sysuser.dto.SysUserSaveDTO;
import yc.star.system.mapper.SysUserMapper;
import yc.star.system.service.ISysUserService;
import yc.star.system.utils.BCryptUtils;

import java.util.List;


@Slf4j
@Service
@RefreshScope
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TokenService tokenService;
    @Value("${jwt.secret}")
    private String secret; // jwt安全密钥

    @Override
    public String login(String userAccount, String password) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getUserId,SysUser::getPassword,SysUser::getNickName).eq(SysUser::getUserAccount, userAccount));
        if (sysUser == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        if (!BCryptUtils.matchesPassword(password,sysUser.getPassword())) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        String token = tokenService.createToken(sysUser.getUserId(), secret, UserIdentity.ADMIN.getValue(),sysUser.getNickName(),null);

        return token;
    }

    @Override
    public boolean logout(String token) {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return tokenService.deleteLoginUser(token, secret);
    }

    @Override
    public int add(SysUserSaveDTO saveDTO) {

        // 查出数据库中是否有名字相同的
        List<SysUser> sysUserList = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, saveDTO.getUserAccount()));
        // 当数据库中存在该用户名
        if (CollectionUtil.isNotEmpty(sysUserList)) {
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }
        // 预制数据
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(saveDTO.getUserAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(saveDTO.getPassword()));
        // 调用mapper,插入管理员
        int rows = sysUserMapper.insert(sysUser);
        return rows;
    }

    @Override
    public LoginUserVo info(String token) {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        if (loginUser == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setNickName(loginUser.getNickName());
        return loginUserVo;
    }

}